import axios from 'axios';
//import Config from "./Config";

//axios.defaults.baseURL = Config.WeiApiAddress;//baseURL将被添加到url前面
axios.defaults.timeout = 30000;// 超时时长
axios.defaults.responseType = 'json';//返回数据类型 包括 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'

axios.interceptors.request.use(request => {//请求拦截器
    //'Authorization': window.localStorage["Token"],
    request.headers['Cache-Control'] = 'no-store';//no-cache;
    request.headers['Content-Type'] = 'application/json;charset=utf-8';
    return request;
}, error => {
    debugger;
    console.log(`axios请求拦截器 报错：${error}`);
});

axios.interceptors.response.use(response => {//响应拦截器
    response.headers['Pragma'] = 'no-cache';
    response.headers['Cache-Control'] = 'no-store';
    response.headers['Expires'] = 0;
    return response;
}, error => {
    debugger;
    console.log(`axios响应拦截器 报错：${error}`);
});

const AxiosCall = async (url, type, data = {}) => {
    type = typeof (type) != "undefined" ? type.toLowerCase() : 'get';

    return await axios({
        url,
        method: type, 
        ...(type === "get" ? { params: data } : { data: JSON.stringify(data) }),
    }).then(res => {
        if (res !== undefined) {
            if (res.status === 200)
                return res.data;  //arrayBuffer()、blob()、formData()、json()、text()
            else
                console.log(`Axios异常状态码：${res.status}`);
        } else
            console.log("Axios Response is undefined");
    }).catch(error => {
        debugger;
        console.log("Axios Catch：", error, JSON.stringify(error));
    });
}

//调用示例
//AxiosCall("http://localhost:40301/api/Default1/Feach", "post", { username: "daea", password: "password" }).then(res => console.log(alert(res)));
//AxiosCall("http://localhost:40301/api/Default1/Feach").then(res => console.log(alert(res)));

//同时发起多个请求时的处理
// axios.all([
//     AxiosCall("http://localhost:40301/api/Default1/Feach1"),
//     AxiosCall("http://localhost:40301/api/Default1/Feach2")
// ]).then(axios.spread(function (res1, res2) { }));       //两个请求现已完成


export default AxiosCall;